package com.sun.module_network


/**
 *@author:sunc
 *@time :2025/7/18 10:58
 *@desc: 自定义异常类
 */
//class ApiException : Exception {
//
//    private var errorMsg: String //错误消息
//    private var errorCode: Long //错误码
//    private var errorLog: String? //错误日志
//
//    constructor(errorCode: Long, error: String?, errorLog: String? = "") : super(error) {
//        this.errorMsg = error ?: "请求失败，请稍后再试"
//        this.errorCode = errorCode
//        this.errorLog = errorLog ?: errorMsg
//    }
//
//    constructor(error: ERROR, e: Throwable?) {
//        errorCode = error.getKey()
//        errorMsg = error.getValue()
//        errorLog = e?.message
//    }
//}


/**
 * 异常基类
 */
open class BaseException(
    val error: Error,
    code: Long=-1000,
    message: String? = null,
    cause: Throwable? = null
) : Exception(message ?: error.defaultMessage, cause)

/**
 * API异常类
 */
open class ApiException(
    error: Error,
    val code: Long=-1000,
    message: String? = null,
    cause: Throwable? = null,
    val context: Map<String, Any> = emptyMap()
) : BaseException(error, code,message, cause) {

    /**
     * 获取格式化后的错误消息
     */
    fun getFormattedMessage(vararg args: Any): String {
        return error.getMessage(*args)
    }

    /**
     * 添加错误上下文
     */
    fun withContext(key: String, value: Any): ApiException {
        return ApiException(
            error = error,
            code = code,
            message = message,
            cause = cause,
            context = context + (key to value)
        )
    }

    /**
     * 获取错误级别
     */
    fun getErrorLevel(): ErrorLevel = error.level
}

/**
 * 业务异常类
 */
class BusinessException(
    error: Error,
    code: Long=-1000,
    message: String? = null,
    cause: Throwable? = null,
    context: Map<String, Any> = emptyMap()
) : ApiException(error, code,message, cause, context)

/**
 * 系统异常类
 */
class SystemException(
    error: Error,
    code: Long=-1000,
    message: String? = null,
    cause: Throwable? = null,
    context: Map<String, Any> = emptyMap()
) : ApiException(error, code,message, cause, context)



